#!/bin/bash
#
#  Volodymyr P Sergiievskyi, voov.rat@gmail.com
#
#  Reorder rism-mol RDFs file to the gvv format which is produced by AmberTools 1DRISM program #
#  Let we have atoms 1,2,3,4
#  and RDFs g11, g12, g13, g14,...
#
#  RISM-MOL order is:
#
#  g11, g12, g13, g14, g22, g23, g24, g33, g34, g44
#
#  AmberTools order is:
#
#  g11, g12, g22, g13, g23, g33, g14, g24, g34, g44
#
#  The orders can be more understandable, if we write the RDFs in the table:
# 
#      1   2    3     4
#  1  g11  g12  g13  g14
#  2       g22  g23  g24
#  3            g33  g34
#  4                 g44
#
#   In RISM-MOL order (rdf file) the RDFs are presented row-by row    
#   In AmberTools (gvv file)  order - column by column
#
#  This script generates the  gawk command to reorder the RDFs and then - run it...
# 

echo USAGE:   ./rismmolRDFs2gvv  mol.rdf mol.gvv

function countCols
{
  echo $#
}

A=$(countCols $(head -n 1 $1))



N=$(echo "scale=10;sqrt(2*($A-1)+1/4)-1/2" | bc | xargs printf "%1.0f" )

#echo $N

K="'"
KK='"'
USD='$'
SP=$KK'\t'$KK

S="gawk $K{ print "$USD"1$SP"

# To transform - we just need write numbers with dynamic stride: 1,2,3... 
# Beginning of each row is 2,4 =1+ 1+2, 7=1+ 3+3, 11=1 + 6+4,... etc (stride grows)
#

rowbegin=2
rowstride=2

for ((i=1;i<=$N;i++))
do
	k=$rowbegin
 	for ((j=$i;j<=$N;j++))
	do
			
		S=$S' $'$k$SP
		k=$(($k+$j))
#		stride=$(($stride-1))		

	done 

	rowbegin=$(( $rowbegin + $rowstride ))
	rowstride=$(( $rowstride + 1 ))
done

S=$S"}'"
#echo $S

S="cat $1 | $S > $2"
#echo $S
eval  $S  

